# —————————————————————————————————————————————————————————————————— #
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("./")
import mymodel
import mymodel.utils as utils


# —————————————————————————————————————————————————————————————————— #
'''超参数'''
mode = "test"
wd = 5e-4 # 权重衰减
pre_len = 1000 # 预测长度
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
batch_size = 64
block_size = 256 # 往前看几个
max_iter = 100 # 训练时的
eval_iter = 100 # 评估loss时的
lr = 3e-4
eval_steps = 200 # 多少评估一次
n_embd = 360 # 词向量维度
n_keys = 360 # 键/查询/值维度（词义维度）
n_heads = 6 # 注意力头数量
n_blocks = 6 # 几个注意力块
dropout = 0.2

# —————————————————————————————————————————————————————————————————— #
'''读入数据'''
with open("./TRANSFORMER/dataset.txt", "r", encoding="utf-8") as f:
    text = f.read()
text_len = len(text)
chars = sorted(list(set(text))) # 提取所有不重复字符并放在一个列表中排序
vocab_size = len(chars)

# —————————————————————————————————————————————————————————————————— #
print(f"----------- {__file__} on device {device} start -----------")

# —————————————————————————————————————————————————————————————————— #
'''解码编码器索引字符相互转化'''
stoi = {ch:idx for idx,ch in enumerate(chars)}
itos = chars
encoder = lambda s: [stoi[c] for c in s]
decoder = lambda idxs: "".join([itos[idx] for idx in idxs])

# —————————————————————————————————————————————————————————————————— #
'''把数据分成训练集和验证集'''
data = torch.tensor(encoder(text), dtype=torch.long) # 全文的索引
n_90 = int(text_len*0.9)
train_data = data[:n_90].to(device)
val_data = data[n_90:].to(device)
# —————————————————————————————————————————————————————————————————— #
'''在评估模式下同时对训练和测试进行损失评估，取几个随机批量的平均值'''
@torch.no_grad()
def estimate_loss():
    out = {}
    model.eval()
    for split in ["train", "val"]:
        losses = torch.zeros(eval_iter)
        for k in range(eval_iter):
            X, Y = get_batch(split)
            _, loss = model(X, Y)
            losses[k] = loss.mean()
        out[split] = losses.mean()
    model.train()
    return out

# —————————————————————————————————————————————————————————————————— #
'''获取一批输入输出 y的位置对应x的target'''
def get_batch(mode="train"):
    (data, data_len) = (train_data, n_90) if mode == "train" else (val_data, text_len-n_90)
    idxs = torch.randint(0, data_len-1-block_size, (batch_size,)) # 生成一个起始索引
    x = torch.stack([data[idx:idx+block_size] for idx in idxs]) # 根据索引生成批量数据(batch_size, block_size)
    y = torch.stack([data[idx+1:idx+block_size+1] for idx in idxs]) # x往后偏移一位
    # x, y = x.to(device), y.to(device)
    return x, y
# —————————————————————————————————————————————————————————————————— #
'''自注意头'''
class MultiHeadAttention(nn.Module):
    # 输入是n_embed, 输出也是n_embed
    def __init__(self, n_embed, n_heads, n_keys, mask=True) -> None:
        super().__init__()
        # n_dims词向量维度
        # n_heads注意力头的数量
        # n_keys 查询/键/值的数量
        assert n_keys % n_heads == 0
        self.n_keys = n_keys
        self.n_heads = n_heads
        self.mask = mask
        self.n_singlehead = n_keys//n_heads
        self.dropout = nn.Dropout(dropout)
        self.W_k = nn.Linear(n_embed, n_keys)
        self.W_q = nn.Linear(n_embed, n_keys)
        self.W_v = nn.Linear(n_embed, n_keys)
        self.fullconnection = nn.Linear(n_keys, n_embed)

    def forward(self, X):
        batch_size = X.shape[0]
        n_vocabs = X.shape[1]
        key = self.W_k(X).view((batch_size, -1, self.n_heads, self.n_singlehead)).transpose(1,2)
        quary = self.W_q(X).view((batch_size, -1, self.n_heads, self.n_singlehead)).transpose(1,2)
        value = self.W_v(X).view((batch_size, -1, self.n_heads, self.n_singlehead)).transpose(1,2)
        # shape (batch_size, n_vocabs, n_keys) 然后拆分成单个head方便计算 shape(batch_size, n_heads, n_vocabs, n_singlehead)
        score = quary @ key.transpose(-1, -2) / self.n_singlehead**0.5 # 这边除以这个东西，使得所有输出的的值都保持在一个合理范围
        # 如果方差太大，softmax会趋向于onehot的形式
        # shape (batch_size, n_heads, n_vocabs, n_vocabs)
        if self.mask:
            mask = (torch.tril(torch.ones((n_vocabs, n_vocabs)))==0).to(device)
            score[:] = torch.masked_fill(score, mask, float('-inf'))
        score[:] = torch.softmax(score, dim=-1)
        out = self.dropout(score)
        # print(score)
        out = score @ value
        # print(out.shape)
        # shape(batch_size, n_heads, n_vocabs, n_singlehead)
        out = torch.transpose(out, 1, 2).contiguous().view((batch_size, -1, self.n_keys))
        out = self.fullconnection(out)
        return out

class Decoder(nn.Module):
    def __init__(self, n_embd, n_head, n_keys) -> None:
        super().__init__()
        self.heads = MultiHeadAttention(n_embd, n_head, n_keys)
        self.sffd = FeedForward(n_embd)
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)

    def forward(self, x):
        # layernorm在论文中是用在后面，但现在一般在前面用
        x = self.heads(self.ln1(x)) + x
        x = self.sffd(self.ln2(x)) + x
        return x
# —————————————————————————————————————————————————————————————————— #
'''前反馈层'''
class FeedForward(nn.Module):
    def __init__(self, n_embd) -> None:
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.ReLU(),
            nn.Linear(4 * n_embd, n_embd),
            nn.Dropout(dropout)
        )
    
    def forward(self, x):
        return self.net(x)

# —————————————————————————————————————————————————————————————————— #
class BigramLanuageModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        # 词嵌入和位置编码
        self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
        self.position_embedding_tabel = nn.Embedding(block_size, n_embd)
        self.blocks = nn.Sequential(*[Decoder(n_embd, n_heads, n_keys) for _ in range(n_blocks)])
        self.ln1 = nn.LayerNorm(n_embd)
        self.lh_linear = nn.Linear(n_embd, vocab_size)

    def forward(self, batch_x, batch_y=None):
        B, T = batch_x.shape
        token_embd = self.token_embedding_table(batch_x) # （B, T, C）
        position_embd = self.position_embedding_tabel(torch.arange(T, device=device)) # （T, C）
        # T 是每个批次的样本token数量
        x = token_embd + position_embd # 广播机制相加（B, T, C）
        x = self.blocks(x) # (B, T, Head_size)
        x = self.ln1(x)
        logits = self.lh_linear(x) #（B, T, vocab_size）

        if batch_y is None:
            loss = None
        else:
            B, T, C  = logits.shape
            loss = F.cross_entropy(logits.view(B*T, C), batch_y.view(B*T))
        return logits, loss
    
    def generater(self, idx, new_tokens_len, realtime=True):
        # 生成时只有一个批次
        # 把所有的idx收集起来是因为后面有根据前面多个预测的模型
        if realtime:
            for _ in range(new_tokens_len):
                idx_in = idx[:, -block_size:]
                logits, _ = self.forward(idx_in)
                # print(logits.shape)
                logits = logits[:, -1]
                # print(logits.shape)
                # 取最后一个因为是二元模型
                probs = nn.functional.softmax(logits, dim=1)
                idx_next = torch.multinomial(probs, 1, True)
                print(decoder(idx_next), end='')
                idx = torch.cat((idx, idx_next), dim=1)
        else:
            for _ in range(new_tokens_len):
                idx_in = idx[:, -block_size:]
                logits, _ = self.forward(idx_in)
                # print(logits.shape)
                logits = logits[:, -1]
                # print(logits.shape)
                # 取最后一个因为是二元模型
                probs = nn.functional.softmax(logits, dim=1)
                idx_next = torch.multinomial(probs, 1, True)
                idx = torch.cat((idx, idx_next), dim=1)
        return idx

# —————————————————————————————————————————————————————————————————— #
@utils.timer
def train():
    print(f"# —————— start training on {device} —————— #")
    for iters in range(max_iter):
        print(f"[iter {iters}]")
        bx, by = get_batch()
        _, loss = model(bx, by)
        optim.zero_grad(set_to_none=True)
        loss.backward()
        optim.step()
        if iters%eval_steps==0:
            losses = estimate_loss()
            print(f"[step {iters}] {losses}")

# —————————————————————————————————————————————————————————————————— #
'''main'''
file_r = "./TRANSFORMER/model/360_360_256_6_6_3100"
file_w = "./TRANSFORMER/model/360_360_256_6_6_3100"
model = BigramLanuageModel().to(device)
optim = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=wd)
model = torch.load(file_r)
if mode=="train":
    train()
    torch.save(model, file_w)
else:
    model = torch.load(file_r)
    inputs = input("输入起始序列\n")
    while(inputs!="q!"):
        test_x = torch.tensor((encoder(inputs))).unsqueeze_(0).to(device)
        model.generater(test_x, pre_len)
        inputs = input("\n输入起始序列\n")
if mode!="test":
    test_x = torch.zeros((1,1), dtype=torch.long, device=device)
    losses = estimate_loss()
    print(f"[loss]:{losses}")
    print(f"[generate test]:{decoder(model.generater(test_x, pre_len)[0].tolist())}")
    print(f"----------- {__file__} on device {device} end -----------")
# —————————————————————————————————————————————————————————————————— #
